package com.pokermadness.servlets;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import com.pokermadness.chat.Chat;

/**
 * Servlet implementation class ChatServlet
 */
@WebServlet("/ChatServlet")
public class ChatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ChatServlet() {
		super();
	}

	public void init() {
		ServletContext context = getServletContext();
		context.setAttribute("active-sessions",
				new HashMap<String, HttpSession>());
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
		@SuppressWarnings("unchecked")
		HashMap<String, HttpSession> map = (HashMap<String, HttpSession>) getServletContext().getAttribute(
		"active-sessions");
		String key = getCookieValue(
				request.getCookies(), "session", "-1");
		if (map.containsKey(key)) {
			session = map.get(key);
		} else {
			session = request.getSession(true);
			map.put(session.getId(), session);
			session.setMaxInactiveInterval(600);
		}
		Chat chat = (Chat) session.getAttribute("chat");
		if (chat == null) {
			chat = new Chat();
			session.setAttribute("chat", chat);
		}
		Cookie cookie = new Cookie("session", session.getId());
		cookie.setMaxAge(600);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		response.setContentType("application/json");
		if(request.getParameterMap().containsKey("message")) {
			sendBotAnswer(request, response, chat);
		} else if(request.getParameterMap().containsKey("getAll")) {
			sendAllMessages(request, response, chat);
		}
	}
	
	private void sendAllMessages(HttpServletRequest request,
			HttpServletResponse response, Chat chat) throws IOException {
		response.getWriter().write(chat.getAllMessages().toString());
	}

	private void sendBotAnswer(HttpServletRequest request,
			HttpServletResponse response, Chat chat) throws IOException {
		String message = request.getParameter("message");
		chat.processMessage(message);
		JSONObject answerObject = chat.getResponse();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// tee midagi
		}
		response.getWriter().write(answerObject.toString());
	}

	private String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		if(cookies == null)
			return defaultValue;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

}
